﻿using DataAchive.Helper;
using DataAchive.Model;
using DataAchive.Model.DBModels;
using DataAchive.Model.ViewModels;
using DataAchive.xamls;
using Microsoft.Win32;
using OpenCvSharp;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Data.Entity.Core.Common.CommandTrees.ExpressionBuilder;
using System.Linq;
using System.Runtime.InteropServices;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Interop;
using System.Windows.Media;
using System.Xml;

namespace DataAchive
{
    /// <summary>
    /// Window1.xaml 的交互逻辑
    /// </summary>
    public partial class NgInfoWindow : System.Windows.Window
    {
        private Helper.DataGridHelper gridHelper = new Helper.DataGridHelper();
        private bool isInitialize = false;
        
        public NgInfoWindow()
        {
            try
            {                
                InitializeComponent();
                if (!string.IsNullOrWhiteSpace(ConnectionHelper.CurrentSiteAddress))
                {
                    this.Title = "Ng查询--->当前集控地址:"+ConnectionHelper.CurrentSiteAddress.Split(';')[0];
                }
                isInitialize = true;
                NgViewModel ngViewModel = new NgViewModel();
                this.DataContext = ngViewModel;
                SoftCommon.Log.Write($"NgInfoWindow");
                var allData = this.DataContext as NgViewModel;
                List<string> checkedColumns = allData.ItemsData.Where(s => s.IsCheck).Select(s => s.ViewName).ToList();
                gridHelper.DataGridBuilder(typeof(NgData),  viewData, checkedColumns);
                SoftCommon.Log.Write($"NgInfoWindow:DataGridBuilder");
                AddDetailButtonColumn();
               
                BingData();

        
            }
            catch (Exception ex)
            {
                SoftCommon.Log.Write(SoftCommon.LogType.Error, $"机台信息初始化异常：" + ex.Message);
            }

        }

        /// <summary>
        /// 列表数据绑定
        /// </summary>
        /// <param name="AllData"></param>
        public void BingData()
        {
            if (this.DataContext == null)
            {
                this.DataContext = new NgViewModel();
            }
            NgViewModel ngViewModel = this.DataContext as NgViewModel;

            List<NgData> resultData = GetBingList(ngViewModel.NgQuery, out int dataCount, ngViewModel.NgInfoData.PageIndex, ngViewModel.NgInfoData.PageSize) ?? new List<NgData>();
            ngViewModel.NgInfoData.Data = new ObservableCollection<NgData>(resultData);
            ngViewModel.NgInfoData.Count = dataCount;
            int pageAdd = 0;
            if (dataCount % (ngViewModel.NgInfoData.PageSize == 0 ? 10 : ngViewModel.NgInfoData.PageSize) != 0)
                pageAdd += 1;
            ngViewModel.NgInfoData.PageCount = dataCount / (ngViewModel.NgInfoData.PageSize == 0 ? 10 : ngViewModel.NgInfoData.PageSize) + pageAdd;
            SoftCommon.Log.Write($"BingData");
        }

        /// <summary>
        /// 获取绑定列表的数据
        /// </summary>
        /// <param name="AllData"></param>
        public List<NgData> GetBingList(NgData QueryModel, out int dataCount, int PageIndex = 0, int PageSize = 0)
        {
            try
            {
                M_QueryBuilder queryBuilder = new M_QueryBuilder();
                List<AChiveSite> aChiveSiteList = new List<AChiveSite>();
                List<AChiveNG> list = new List<AChiveNG>();
                PageModel<AChiveNG> pageList = new PageModel<AChiveNG>();
                List<FilterModel> filterList = new List<FilterModel>();
                if (!string.IsNullOrEmpty(QueryModel.Line_Id))
                    filterList.Add(new FilterModel() { Type = FilterType.Like, Name = "line_id", Like = QueryModel.Line_Id });
                if (!string.IsNullOrEmpty(QueryModel.Equipment_Id))
                    filterList.Add(new FilterModel() { Type = FilterType.Like, Name = "equipment_id", Like = QueryModel.Equipment_Id });
                

                if (filterList != null && filterList.Any())
                {
                    aChiveSiteList = queryBuilder.GetModelList(new AChiveSite(), filterList);
                    if (aChiveSiteList == null || !aChiveSiteList.Any())
                        list = new List<AChiveNG>();
                    //pageList = new PageModel<AChiveNG>();
                    else
                    {
                        List<int?> siteIds = aChiveSiteList.Select(s => s.Id).ToList();
                        filterList = new List<FilterModel>();
                        filterList.Add(new FilterModel() { Name = "site_id", Type = FilterType.In, In = siteIds.Cast<object>().ToArray() });
                        if (!string.IsNullOrEmpty(QueryModel.Lot_Id))
                            filterList.Add(new FilterModel() { Name = "lotid", Type = FilterType.Like, Like = QueryModel.Lot_Id });
                        pageList = queryBuilder.GetPageModelList(new AChiveNG(), filterList, PageIndex, PageSize);
                        //list = queryBuilder.GetModelList(new AChiveNG(), filterList);
                    }

                }
                else
                {
                    if (!string.IsNullOrEmpty(QueryModel.Lot_Id))
                        filterList.Add(new FilterModel() { Name = "lotid", Type = FilterType.Like, Like = QueryModel.Lot_Id });
                    pageList = queryBuilder.GetPageModelList(new AChiveNG(), filterList, PageIndex, PageSize);
                    //list = queryBuilder.GetModelList(new AChiveNG(), filterList);
                    List<int?> siteIds = list.Select(s => s.Site_Id).ToList();
                    aChiveSiteList = queryBuilder.GetModelList(
                                   new AChiveSite(),
                                   new List<FilterModel>(){
                                       new FilterModel() { Type = FilterType.In,Name = "Id",In = siteIds.Cast<object>().ToArray()  }
                                   });
                }
                SoftCommon.Log.Write($"GetModelList");

                List<NgData> resultData = new List<NgData>();
                pageList.Data.ForEach(x =>
                //list.ForEach(x =>
                {
                    AChiveSite siteInfo = aChiveSiteList.Find(f => f.Id == x.Site_Id);
                    NgData ng = new NgData();
                    ng.ID = Convert.ToInt32(x.ID ?? 0);
                    ng.Line_Id = siteInfo?.Line_Id;
                    ng.Equipment_Id = siteInfo?.Equipment_Id;
                    ng.IP = siteInfo?.IP;
                    ng.Lot_Id = x.Lot_Id;
                    ng.Info = x.Info;
                    ng.Image = x.Image;
                    ng.Checked = Convert.ToBoolean(x.Checked ?? 0) ? "是" : "否";
                    ng.Date = x.Date?.ToString("yyyy-MM-dd HH:mm:ss");
                    ng.Type = x.Type == 0 ? "EL" : "VI";
                    ng.AI_Info = x.AI_Info;
                    ng.Finish_Time = x.Finish_Time?.ToString("yyyy-MM-dd HH:mm:ss");
                    ng.AI_Result = x.AI_Result;
                    ng.Manua_Result = x.Manua_Result;
                    ng.Mes_Check = x.Mes_Check;

                    ng.Site_Id = Convert.ToInt32(x.Site_Id);
                    ng.Row_Number = siteInfo.Row_Number?.ToString();
                    ng.Row_Type = siteInfo.Row_Type?.ToString();
                    ng.Row_Order = siteInfo.Row_Order;
                    ng.Column_Number = siteInfo.Colum_Number?.ToString();
                    ng.Column_Type = siteInfo.Colum_Type?.ToString();
                    ng.Column_Order = siteInfo.Colum_Order;
                    ng.Top_Bottom_Margin = siteInfo.Top_Bottom_Margin?.ToString();
                    ng.Left_Right_Margin = siteInfo.Left_Right_Margin?.ToString();
                    ng.Shift_Start_Time = siteInfo.Shift_Start_Time;
                    ng.Shifting = siteInfo.Shiftings.ToString();
                    ng.Currentshift = siteInfo.Cuttent_Shift.ToString();
                    resultData.Add(ng);
                });
                dataCount = pageList.Count;
                //dataCount = list.Count;
                return resultData;
            }
            catch (Exception ex)
            {
                SoftCommon.Log.Write(SoftCommon.LogType.Error, $"表格数据加载异常：" + ex.Message);
                dataCount = 0;
                return default;
            }

        }

        /// <summary>
        /// 查询按钮点击事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Select_Click(object sender, RoutedEventArgs e)
        {
            SoftCommon.Log.Write($"查询按钮点击");
            BingData();
        }
        /// <summary>
        /// 导出按钮点击事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Exprot_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                SoftCommon.Log.Write($"导出按钮点击");
                string path = string.Empty;
                // 创建 FolderBrowserDialog 对话框实例
                using (System.Windows.Forms.FolderBrowserDialog folderDialog = new System.Windows.Forms.FolderBrowserDialog())
                {
                    // 显示对话框，并等待用户选择文件夹
                    System.Windows.Forms.DialogResult result = folderDialog.ShowDialog();

                    // 如果用户点击了确定按钮，获取选定的文件夹路径并显示在界面上
                    if (result == System.Windows.Forms.DialogResult.OK)
                    {
                        path = folderDialog.SelectedPath;
                    }
                }
                SoftCommon.Log.Write($"用户选择文件保存地址：{path}");
                if (string.IsNullOrWhiteSpace(path))
                {
                    return;
                }

                string fileName = $@"{path}\Ng-{DateTime.Now.ToString("yyyyMMddHHmmss")}.xlsx";
                NgViewModel ngViewModel = this.DataContext as NgViewModel;
                //List<NgExportViewModel> dataList = ngViewModel.NgInfoData.Select(s => new NgExportViewModel()
                //{
                //    ID = Convert.ToInt32(s.ID ?? 0),
                //    Lot_Id = s.Lot_Id,
                //    Info = s.Info,
                //    Image = s.Image,
                //    Checked = s.Checked,
                //    Date = s.Date,
                //    Type = s.Type,
                //    AI_Info = s.AI_Info,
                //    Site_Id = s.Site_Id,
                //    Finish_Time = s.Finish_Time,
                //    AI_Result = s.AI_Result,
                //    Manua_Result = s.Manua_Result,
                //    Mes_Check = s.Mes_Check
                //}).ToList();

                var allData = this.DataContext as NgViewModel;
                List<string> checkedColumns = allData.ItemsData.Where(s => s.IsCheck).Select(s => s.ViewName).ToList();
                var data = GetBingList(allData.NgQuery, out int count,PageSize:10000);
                ExcelHelper.ExportColumn(fileName, data, checkedColumns, "缺陷信息");
                SoftCommon.Log.Write($"导出文件保存成功！");
                FileHelper folderHelper = new FileHelper();
                folderHelper.OpenFolder(path);
            }
            catch (Exception ex)
            {
                SoftCommon.Log.Write(SoftCommon.LogType.Error, $"导出异常：" + ex.Message);
            }

        }


        private static InfoWindow infoWindow;
        internal static StatisticsWindow statisticsWindow;
        /// <summary>
        /// 列表详情按钮点击事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Info_Click(object sender, RoutedEventArgs e)
        {
            SoftCommon.Log.Write($"Info_Click");
            object data = ((Button)sender).CommandParameter as NgData;
            if (infoWindow == null || !infoWindow.IsVisible)
            {
                object[] param = { new object[] { data } };
                // ActivatorHelper.GetInstance<InfoWindow>(ref infoWindow, param);
                // infoWindow.Closed += (s, eventArgs) => infoWindow = null; // 当 SecondWindow 关闭时释放资源
                InfoWindow infoWindow = new InfoWindow(param);
                infoWindow.Closed += (s, eventArgs) =>
                {
                   
                };
               
                infoWindow.ShowDialog();               
            }
            else
            {
                infoWindow.Activate(); // 如果 SecondWindow 已经存在，则激活它
            }

        }

        private void SetColumn_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                SoftCommon.Log.Write($"列筛选按钮点击");
                var allData = this.DataContext as NgViewModel;
                List<string> checkedColumns = allData.ItemsData.Where(s => s.IsCheck).Select(s => s.ViewName).ToList();

                // 清除已有的列
                viewData.Columns.Clear();
                SoftCommon.Log.Write($"清除页面Table信息");

                gridHelper.DataGridBuilder(typeof(NgData),  viewData, checkedColumns);
                SoftCommon.Log.Write($"重新根据列头创建表格");
                AddDetailButtonColumn();
                SoftCommon.Log.Write($"明细按钮创建");
                BingData();
                SoftCommon.Log.Write($"数据绑定");
            }
            catch (Exception ex)
            {
                SoftCommon.Log.Write(SoftCommon.LogType.Error, $"列头筛选异常：" + ex.Message);
            }

        }



        private void AddDetailButtonColumn()
        {
            // 创建 DataGridTemplateColumn 列
            DataGridTemplateColumn templateColumn = new DataGridTemplateColumn();
            templateColumn.Width = new DataGridLength(1, DataGridLengthUnitType.Star); // 设置列宽为自动调整

            // 创建 CellTemplate
            FrameworkElementFactory buttonFactory = new FrameworkElementFactory(typeof(Button));
            buttonFactory.SetValue(Button.ContentProperty, "明细");
            buttonFactory.AddHandler(Button.ClickEvent, new RoutedEventHandler(Info_Click));

            // 设置按钮的 CommandParameter 属性为当前行的数据
            buttonFactory.SetBinding(Button.CommandParameterProperty, new Binding());

            // 创建 DataTemplate 并设置 CellTemplate
            DataTemplate cellTemplate = new DataTemplate();
            cellTemplate.VisualTree = buttonFactory;
            templateColumn.CellTemplate = cellTemplate;

            // 添加列到 DataGrid
            viewData.Columns.Add(templateColumn);
        }


        #region 图像压缩按钮点击（旧）
        private void ImageCompression_Click(object sender, RoutedEventArgs e)
        {
            string path = string.Empty;
            // 创建 OpenFileDialog 实例
            OpenFileDialog openFileDialog = new OpenFileDialog();

            // 设置对话框的属性
            openFileDialog.Title = "选择图像文件";
            openFileDialog.Filter = "图像文件 (*.jpg; *.jpeg; *.png; *.bmp)|*.jpg; *.jpeg; *.png; *.bmp|所有文件 (*.*)|*.*";
            openFileDialog.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyPictures);

            // 显示对话框并获取结果
            bool? result = openFileDialog.ShowDialog();

            // 检查用户是否成功选择文件
            if (result == true)
            {
                // 获取选定文件的文件名
                string selectedFilePath = openFileDialog.FileName;
                string fileName = openFileDialog.SafeFileName;
                CompressionImage(selectedFilePath, fileName);
                // 在这里可以处理选定的文件，例如加载图像或执行其他操作
            }

        }

        private void CompressionImage(string filePath, string FileName)
        {
            // 读取原始图像
            Mat originalImage = Cv2.ImRead(filePath, ImreadModes.Color);

            // 调整图像大小
            int targetWidth = 800; // 目标宽度
            int targetHeight = (int)(originalImage.Rows * ((double)targetWidth / originalImage.Cols)); // 根据比例计算目标高度
            Mat resizedImage = new Mat();
            Cv2.Resize(originalImage, resizedImage, new OpenCvSharp.Size(targetWidth, targetHeight));


            string path = string.Empty;
            // 创建 FolderBrowserDialog 对话框实例
            using (System.Windows.Forms.FolderBrowserDialog folderDialog = new System.Windows.Forms.FolderBrowserDialog())
            {
                folderDialog.Description = "选择要保存文件的文件夹";
                // 显示对话框，并等待用户选择文件夹
                System.Windows.Forms.DialogResult result = folderDialog.ShowDialog();

                // 如果用户点击了确定按钮，获取选定的文件夹路径并显示在界面上
                if (result == System.Windows.Forms.DialogResult.OK)
                {
                    path = folderDialog.SelectedPath;
                }

                path = FileHelper.GetFileName(path, FileName);
                // 保存调整大小后的图像
                Cv2.ImWrite($@"{path}", resizedImage);

                // 释放图像资源
                originalImage.Dispose();
                resizedImage.Dispose();
                MessageBox.Show("文件保存成功！");
            }

        }
        #endregion
        private T FindVisualChild<T>(DependencyObject parent) where T : DependencyObject
        {
            for (int i = 0; i < VisualTreeHelper.GetChildrenCount(parent); i++)
            {
                var child = VisualTreeHelper.GetChild(parent, i);
                if (child != null && child is T tChild)
                {
                    return tChild;
                }

                var childOfChild = FindVisualChild<T>(child);
                if (childOfChild != null)
                {
                    return childOfChild;
                }
            }
            return null;
        }

        private void Pagination_CurrentIndexChanged(object sender, Panuon.UI.Silver.Core.CurrentIndexChangedEventArgs e)
        {
            //Panuon.UI.Silver.Pagination pagination = sender as Panuon.UI.Silver.Pagination;
            //NgViewModel data = this.DataContext as NgViewModel;
            //data.NgInfoData.PageIndex = pagination.CurrentIndex;
            //this.pagination.TotalIndex = data.PageCount;
            BingData();
            //System.Windows.Forms.MessageBox.Show($"TotalIndex:{pagination.TotalIndex},CurrentIndex:{pagination.CurrentIndex}");
        }

        private void ComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (!isInitialize)
                return;
            ComboBox comboBox = sender as ComboBox;
            if (comboBox.SelectedItem != null)
            {
                ComboBoxItem selectedItem = (ComboBoxItem)comboBox.SelectedItem;
                int selectedTag = Convert.ToInt32(selectedItem.Tag);
                NgViewModel data = this.DataContext as NgViewModel;
                data.NgInfoData.PageIndex = 1;
                data.NgInfoData.PageSize = selectedTag;
                BingData();
            }
        }

        internal static StatisticsViWindow statisticsViWindow;
        private void Statistics_Click(object sender, RoutedEventArgs e)
        {
            if (statisticsWindow == null || !statisticsWindow.IsVisible)
            {
                ActivatorHelper.GetInstance<StatisticsWindow>(ref statisticsWindow);
                statisticsWindow.Closed += (s, eventArgs) =>
                {
                    statisticsWindow = null; // 当 Window 关闭时释放资源
                    
                };
              
               
               
                statisticsWindow.Show();
            }
            else
            {
                statisticsWindow.Activate(); // 如果 Window 已经存在，则激活它
            }
            statisticsWindow.Show();

            if (statisticsViWindow == null || !statisticsViWindow.IsVisible)
            {
                ActivatorHelper.GetInstance<StatisticsViWindow>(ref statisticsViWindow);
                statisticsViWindow.Closed += (s, eventArgs) => statisticsViWindow = null; // 当 Window 关闭时释放资源
               // statisticsViWindow.Show();
            }
            else
            {
                statisticsViWindow.Activate(); // 如果 Window 已经存在，则激活它
            }
            statisticsViWindow.Show();
        }


        protected override void OnClosed(EventArgs e)
        {
            base.OnClosed(e);
            if(statisticsWindow != null)
            {
                statisticsWindow.Close();
            }
            if(statisticsViWindow != null)
            {
                statisticsViWindow.Close();
            }
    
        }


        // 自定义属性用于控制关闭按钮的状态
        private bool _closeButtonDisabled;
        public bool CloseButtonDisabled
        {
            get => _closeButtonDisabled;
            set
            {
                _closeButtonDisabled = value;
                if (_closeButtonDisabled)
                {
                    // 禁用关闭按钮
                    this.SourceInitialized += (s, args) =>
                    {
                        var hwndSource = PresentationSource.FromVisual(this) as HwndSource;
                        if (hwndSource != null)
                        {
                            var hwnd = hwndSource.Handle;
                            NativeMethods.EnableWindow(hwnd, false);
                        }
                    };
                }
                else
                {
                    // 恢复关闭按钮
                    this.SourceInitialized -= (s, args) =>
                    {
                        var hwndSource = PresentationSource.FromVisual(this) as HwndSource;
                        if (hwndSource != null)
                        {
                            var hwnd = hwndSource.Handle;
                            NativeMethods.EnableWindow(hwnd, true);
                        }
                    };
                }
            }
        }

        // 封装 Win32 API 的静态类
        internal static class NativeMethods
        {
            [DllImport("user32.dll", SetLastError = true)]
            public static extern bool EnableWindow(IntPtr hWnd, bool bEnable);
        }

        private void printData_Click(object sender, RoutedEventArgs e)
        {
            var priviewDialog = new System.Windows.Forms.PrintPreviewDialog();
            var printDocument =new System.Drawing.Printing.PrintDocument();
            printDocument.PrintPage += PrintDocument_PrintPage;
            priviewDialog.ShowDialog();
        }

        private void PrintDocument_PrintPage(object sender, System.Drawing.Printing.PrintPageEventArgs e)
        {
           
        }

        private void PrintBtn_Click(object sender, RoutedEventArgs e)
        {
            List<NgData> ngDatas = new List<NgData>()
            {
                 new NgData()
                 {
                      Lot_Id="p12333",
                       Equipment_Id="a912-1",
                        AI_Result="OK",
                         Manua_Result="NG",
                 }
            };
            var dv= this.DataContext as NgViewModel;
            Preview preview = new Preview("/xamls/NgFlow.xaml", dv.NgInfoData.Data.ToList(), new NgDocRender() );
            preview.Owner = this;
            preview.ShowInTaskbar = false;
            preview.ShowDialog();
        }
    }
}
